home *** CD-ROM | disk | FTP | other *** search
- #include <stdio.h>
- #include <stdlib.h>
-
- typedef int Card;
-
- typedef int Suit;
- typedef int Rank;
-
- #define CLUBS 1
- #define DIAMONDS 2
- #define SPADES 3
- #define HEARTS 4
- #define FIRST_SUIT 1
- #define LAST_SUIT 4
-
- Card make_card( Suit suit, Rank rank )
- {
- return (suit << 4) + rank;
- }
-
- Suit card_suit( Card c )
- {
- return c >> 4;
- }
-
- Rank card_rank( Card c )
- {
- return c & 0xf;
- }
-
- Card pack[52];
-
- void initialise_pack(void)
- {
- Suit s;
- Rank r;
- int i = 0;
- for (s = FIRST_SUIT; s <= LAST_SUIT; s++)
- for (r = 1; r < 14; r++)
- pack[ i++ ] = make_card( s, r );
- }
-
- void shuffle_pack(void)
- {
- int i;
- for (i = 51; i != 0; i--)
- {
- int j = rand() % (i + 1);
- if (i != j)
- {
- Card c = pack[i];
- pack[i] = pack[j];
- pack[j] = c;
- }
- }
- }
-
- char *ranks = "?A23456789TJQK";
-
-
- char *suits[] =
- {
- "(no suit)",
- "clubs",
- "diamonds",
- "spades",
- "hearts"
- };
-
- void print_card( Card c )
- {
- printf
- (
- "%c of %s",
- ranks[ card_rank( c ) ],
- suits[ card_suit( c ) ]
- );
- }
-
- void print_pack(void)
- {
- int i;
- for (i = 0; i < 52; i++)
- {
- print_card( pack[i] );
- printf( "\n" );
- }
- }
-
- typedef struct
- {
- int length;
- Card cards[13];
- }
- Holding;
-
- typedef Holding Hand;
-
- void clear_hand( Hand *h );
-
- void give_card( Hand *h, Card c );
-
- void print_hand( Hand *h );
-
- #define PLAYERS 4
-
- Hand players[PLAYERS];
-
- void deal_cards(void)
- {
- int i = 0, player, card;
- for (player = 0; player < PLAYERS; player++)
- for (card = 0; card < 13; card++)
- give_card( &players[player], pack[i++] );
- }
-
- void print_hands(void)
- {
- int player;
- for (player = 0; player < PLAYERS; player++)
- {
- printf( "Hand for player %d\n", player );
- print_hand( &players[player] );
- }
- }
-
- void clear_hand( Hand *hand )
- {
- (*hand).length = 0;
- }
-
- void give_card( Hand *hand, Card c )
- {
- hand->cards[ hand->length++ ] = c;
- }
-
- void print_hand( Hand *hand )
- {
- int i = hand->length;
- while (i > 0)
- {
- print_card( hand->cards[--i] );
- printf( "\n" );
- }
- }
-
- int main( int argc, char *argv[] )
- {
- initialise_pack();
- shuffle_pack();
- printf( "Shuffled pack:\n" );
- print_pack();
- deal_cards();
- printf( "Dealt hands:\n" );
- print_hands();
- }
-
-